﻿#region Copyright (c) 2008 plexBB Team
/*  Copyright (c) 2008 plexBB Team
 *  
 *  This file is free software: you may copy, redistribute and/or modify it  
 *  under the terms of the GNU General Public License as published by the  
 *  Free Software Foundation, either version 2 of the License, or (at your  
 *  option) any later version.  
 *  
 *  This file is distributed in the hope that it will be useful, but  
 *  WITHOUT ANY WARRANTY; without even the implied warranty of  
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  
 *  General Public License for more details.  
 *  
 *  You should have received a copy of the GNU General Public License  
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */
#endregion

using System.CodeDom;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PlexBB
{
    [ExpressionPrefix("Icons")]
    public class IconsExpressionBuilder : ExpressionBuilder
    {
        public static object EvaluateExpression(string image, Control target)
        {
            // TODO: use Style object to resolve images
            string url = string.Format("{0}/Resources/AdminStyle/Images/{1}.gif",
                PlexBBContext.Current.Configuration.BaseDir.TrimEnd('/'), image.ToLower());

            if (target is Image)
            {
                return url;
            }
            return target.ResolveUrl(url);
        }

        public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            return EvaluateExpression(entry.Expression, (Control)target);
        }

        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            // yes, generally this is a hack into ASP.NET internals:
            // we use @__ctrl variable, that is emitted by ASP.NET compiler
            // any better approach is always welcome
            return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(GetType()), "EvaluateExpression",
                new CodePrimitiveExpression(entry.Expression),
                new CodeVariableReferenceExpression("@__ctrl"));
        }

        public override bool SupportsEvaluate
        {
            get { return true; }
        }
    }
}
